package com.yuanjing.xiangqinxiangai.plugin


import android.app.Activity
import android.app.Application
import android.util.Log
import com.baidu.idl.face.api.manager.FaceServiceManager
import com.baidu.idl.face.platform.FaceEnvironment
import com.baidu.idl.facelive.api.FaceLiveManager
import com.baidu.idl.facelive.api.entity.FaceLiveConfig
import com.baidu.idl.facelive.api.entity.FaceLivenessType
import com.baidu.idl.facelive.api.entity.LivenessValueModel
import com.baidu.ocr.api.util.FileUtil
import com.blankj.utilcode.util.LogUtils
import com.yuanjing.xiangqinxiangai.plugin.auth.ConsoleConfig
import com.yuanjing.xiangqinxiangai.plugin.auth.ConsoleConfigManager
import com.yuanjing.xiangqinxiangai.setting.auth.Config
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.EventChannel.EventSink
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugins.webviewflutter.ConsoleMessageLevel
import java.util.concurrent.Executors

class FaceRecognitionPlugin(private var mActivity: Activity, messenger: BinaryMessenger?) :
    MethodCallHandler, ActivityAware, EventChannel.StreamHandler {
    private lateinit var consoleConfig: ConsoleConfig


    companion object {}

    private var application: Application
    private val mMethodChannel: MethodChannel
    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "init" -> init(call, result)
            "destroy" -> destroy(call, result)
            "takeFace" -> takeFace(call, result)
            else -> result.notImplemented()
        }
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        mActivity = binding.activity
        application = mActivity.application
    }

    override fun onDetachedFromActivityForConfigChanges() {}
    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {}
    override fun onDetachedFromActivity() {}
    private var mEventSink: EventSink? = null

    init {
        application = mActivity.application
        mMethodChannel = MethodChannel(messenger!!, "FaceRecognitionPlugin")
        mMethodChannel.setMethodCallHandler(this)
    }

    override fun onListen(arguments: Any, events: EventSink) {
        mEventSink = events
    }

    override fun onCancel(arguments: Any) {
        mEventSink = null
    }

    private fun init(call: MethodCall, result: MethodChannel.Result) {
        FaceServiceManager.getInstance().init(
            mActivity, Config.LICENSE_KEY, Config.LICENSE_NAME, Config.KEY_NAME,
        ) { resultCode, resultMsg ->
            if (resultCode == 1000) {
                result.success(true)
            } else {
                result.success(false)
                Log.i("FaceServiceManager", "人脸认证初始化失败: $resultMsg($resultCode)")
            }
        }
    }

    private fun destroy(call: MethodCall, result: MethodChannel.Result) {
        FaceServiceManager.release()
        result.success(true)

    }

    private fun takeFace(call: MethodCall, result: MethodChannel.Result) {
        setFaceQualityConfig()
        val params = mutableMapOf<String, Any>()
        params["access_token"] = call.argument<String>("access_token") ?: ""
        params["plan_id"] = "19545"
        params["name"] = call.argument<String>("name") ?: ""
        params["id_card_number"] = call.argument<String>("code") ?: ""
        params["verify_type"] = 0
        params["quality_control"] = "NORMAL"
        params["liveness_control"] = "NORMAL"
        FaceServiceManager.getInstance()
            .startFaceLiveness(mActivity, params) { resultCode, resultMap ->
                LogUtils.e("zz", "code: $resultCode data: $resultMap")

                if (resultCode == 0) {
                    val data = resultMap["data"]
                    val xDeviceId = resultMap["xDeviceId"]
                    val sKey = resultMap["sKey"]
                    result.success(
                        mapOf(
                            "data" to data,
                            "xDeviceId" to xDeviceId,
                            "sKey" to sKey,
                        )
                    )
                } else{
                    result.success(mapOf<String, Any?>())
                }

            }
    }

    private fun setFaceQualityConfig() {
        consoleConfig = ConsoleConfigManager.getInstance(mActivity).config!!
        try {
            val faceLiveConfig = FaceLiveConfig()
            // faceUI默认展示结果页，此处必须设置为false
            faceLiveConfig.isShowResultView = false
            // 设置模糊度阈值
            faceLiveConfig.blurnessValue = consoleConfig.blur
            // 设置最小光照阈值（范围0-255）
            faceLiveConfig.brightnessValue = consoleConfig.illumination
            // 设置最大光照阈值（范围0-255）
            faceLiveConfig.brightnessMaxValue = consoleConfig.maxIllumination
            // 设置左眼遮挡阈值
            faceLiveConfig.occlusionLeftEyeValue = consoleConfig.leftEyeOcclu
            // 设置右眼遮挡阈值
            faceLiveConfig.occlusionRightEyeValue = consoleConfig.rightEyeOcclu
            // 设置鼻子遮挡阈值
            faceLiveConfig.occlusionNoseValue = consoleConfig.noseOcclu
            // 设置嘴巴遮挡阈值
            faceLiveConfig.occlusionMouthValue = consoleConfig.mouthOcclu
            // 设置左脸颊遮挡阈值
            faceLiveConfig.occlusionLeftContourValue = consoleConfig.leftCheekOcclu
            // 设置右脸颊遮挡阈值
            faceLiveConfig.occlusionRightContourValue = consoleConfig.rightCheekOcclu
            // 设置下巴遮挡阈值
            faceLiveConfig.occlusionChinValue = consoleConfig.chinOcclu
            // 设置人脸姿态Pitch阈值
            faceLiveConfig.headPitchValue = consoleConfig.pitch
            // 设置人脸姿态Yaw阈值
            faceLiveConfig.headYawValue = consoleConfig.yaw
            // 设置人脸姿态Roll阈值
            faceLiveConfig.headRollValue = consoleConfig.roll
            // 是否开启录制视频
            faceLiveConfig.isOpenRecord = false
            // 设置是否显示超时弹框
            faceLiveConfig.setIsShowTimeoutDialog(true)
            // 输出图片类型：0原图、1抠图
            faceLiveConfig.outputImageType = FaceEnvironment.VALUE_OUTPUT_IMAGE_TYPE
            // 是否忽略录制异常（只能忽略采集时间过短，采集后无文件输出的异常）
            faceLiveConfig.isIgnoreRecordError = true
            // 眨眼张嘴遮挡开关
            faceLiveConfig.isActiveStrict = true
            // 设置是否开启动作不通过时切换其它动作
            faceLiveConfig.isChangeAction = FaceEnvironment.IS_CHANGE_ACTION
            // 默认简体中文ZH_CN,设置英文文案EN
            faceLiveConfig.isLivenessLanguage = "ZH_CN"
            // 是否展示中英文切换按钮
            faceLiveConfig.isShowLanguageSwitch = false
            // 设置姓名
            faceLiveConfig.name = ""
            // 设置身份证号
            faceLiveConfig.idcardNumber = ""
            // 设置活体类型相关
            setFaceLivenessConfig(faceLiveConfig)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun setFaceLivenessConfig(faceLiveConfig: FaceLiveConfig) {
        try {
            // 设置活体类型：炫彩活体、动作活体、静默活体
            var faceLivenessType: FaceLivenessType? = null
            // 配置活体动作集合、动作个数，活体阈值，无活体
            var livenessValueModel: LivenessValueModel? = null
            if (consoleConfig.faceLiveType === 0) {
                faceLivenessType = FaceLivenessType.COLORLIVENESS
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(true)
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(true)
                livenessValueModel = faceLiveConfig.livenessValueModel
                livenessValueModel.actionList.addAll(consoleConfig.getActions())
                livenessValueModel.livenessScore = consoleConfig.liveScore
            } else if (consoleConfig.faceLiveType === 1) {
                faceLivenessType = FaceLivenessType.ACTIONLIVENESS
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(false)
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(true)
                livenessValueModel = faceLiveConfig.livenessValueModel
                livenessValueModel.actionList.addAll(consoleConfig.getActions())
                livenessValueModel.actionRandomNumber = consoleConfig.faceActionNum
                livenessValueModel.livenessScore = consoleConfig.liveScore
            } else if (consoleConfig.faceLiveType === 2) {
                faceLivenessType = FaceLivenessType.SILENTLIVENESS
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(false)
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(false)
                livenessValueModel = faceLiveConfig.livenessValueModel
                livenessValueModel.livenessScore = consoleConfig.liveScore
            } else if (consoleConfig.faceLiveType === 3) {
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(true)
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(false)
                livenessValueModel = faceLiveConfig.livenessValueModel
            }
            // faceLiveConfig.setFaceLivenessType(faceLivenessType, livenessValueModel);
            faceLiveConfig.livenessValueModel = livenessValueModel
            FaceLiveManager.getInstance().faceConfig = faceLiveConfig
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


}
